package com.cjzuji.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cjzuji.rental.Bean.RenRZuRequest;
import com.cjzuji.rental.Config.RRZConfig;
import com.cjzuji.rental.dao.RenRZuBillDao;
import com.cjzuji.rental.dao.RenRZuContractDao;
import com.cjzuji.rental.dao.RenRZuOrderDao;
import com.cjzuji.rental.dao.RenRZuUserDao;
import com.cjzuji.rental.mapper.OrderBillMapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.pojo.Orders;
import com.cjzuji.rental.service.ErSRRZService;
import com.cjzuji.rental.util.ErSRRZBillUtil;
import com.cjzuji.rental.util.RenRZuBillUtil;
import com.cjzuji.rental.util.Tool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class ErSRRZServiceImpl implements ErSRRZService {

    @Autowired
    RenRZuContractDao RenRZuContractDao;
    @Autowired
    RenRZuOrderDao RenRZuOrderDao;
    @Autowired
    RenRZuBillDao RenRZuBillDao;
    @Autowired
    RenRZuUserDao RenRZuUserDao;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    ErSRRZBillUtil renRZuBillUtil;
    @Autowired
    RRZConfig rrzConfig;
    @Autowired
    ErSRRZSaveServiceImpl orderSaveServiceImpl;
    @Autowired
    OrderBillMapper orderBillMapper;

    private static final Logger logger = LoggerFactory.getLogger(ErSRRZServiceImpl.class);
    @Override
    public List<Map<String, Object>> getRenRZuList(String  authorization,String cookie) {
        String url = rrzConfig.getGetListUrl();
        RenRZuRequest renRZuRequest = new RenRZuRequest();
        List<Map<String, Object>> listData = new ArrayList<>();

        renRZuRequest.setPage_id("68f88da7469209638");
        renRZuRequest.setFrontEndCacheSalesAfterWo("10004");
        renRZuRequest.setList_type(1);
        renRZuRequest.setServer_sort_type(1);
        renRZuRequest.setReturning_sort_type(1);
        renRZuRequest.setWait_send_part_order(0);
        renRZuRequest.setCtrl_ver(1);
        renRZuRequest.setType("all");
        renRZuRequest.setPer_page(15);
        renRZuRequest.setPage(1);
        int pageNum = 1 ;
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                renRZuRequest.setPage(pageNum);
                String resStr = Tool.getRequest(url,"",authorization, "", "", renRZuRequest);
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("order_list");
                Map<String, Object> pagination = (Map<String, Object>) dataMap.get("pagination");
                int page = Integer.parseInt(pagination.get("page").toString());
                int total = Integer.parseInt(pagination.get("total").toString());
                int pageSize = Integer.parseInt(pagination.get("page_size").toString());
                //logger.info("list~~~~~~~ {}",list);
                if(list != null && list.size() > 0){
                    for (Map<String, Object> item : list) {
                        //logger.info("item~~~ {}",item);
                        Map<String, Object> detail = (Map<String, Object>)item.get("base_info");
                        Map<String, Object> amountlist = (Map<String, Object>) item.get("rent_info");
                        //logger.info("amountlist~~~~~ {}",amountlist);
                        if (detail != null && amountlist != null){
                            //订单id
                            String orderId = detail.get("order_id").toString();
                            String uesrName = getUserName(authorization,orderId);
                            String userPhone = getUserPhone(authorization,orderId);
                            String userAddress = getUserAddress(authorization,orderId);
                            String userIdcard = getUserIdcard(authorization,orderId);
                            //合同
                            List<Map<String, Object>> contract = getContractAddress(authorization,orderId);
                            //logger.info("contract {}",contract);
                            //账单
                            List<Map<String, Object>> bill = renRZuBillUtil.getRenRZuBillList(authorization,orderId,cookie);
                            //System.out.println("bill~~"+ bill);
                            // 抽离
                            orderSaveServiceImpl.extractionSave(item,detail,amountlist,contract,bill,authorization,orderId,uesrName,userPhone,userIdcard,userAddress);
                        }
                    }
                }
                //判断当page*pageSize >= total总数量：跳出循环
                if(page*pageSize >= total){
                    logger.info("已经打印完毕");
                    break;

                }
                //休息十秒
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    logger.warn("Sleep interrupted", e);
                    Thread.currentThread().interrupt();
                }
                pageNum ++;
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
            logger.info("打印当前页码 {}",pageNum);
        }
        return listData;
    }

    //租用中
    @Override
    public List<Map<String, Object>> upDateBillList(String  authorization,String cookie) {
        String url = rrzConfig.getGetListUrl();
        RenRZuRequest renRZuRequest = new RenRZuRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        renRZuRequest.setPage_id("68ad5ddaaa21b3989");
        renRZuRequest.setFrontEndCacheSalesAfterWo("10004");
        renRZuRequest.setList_type(1);
        renRZuRequest.setServer_sort_type(1);
        renRZuRequest.setReturning_sort_type(1);
        renRZuRequest.setWait_send_part_order(0);
        renRZuRequest.setCtrl_ver(1);
        renRZuRequest.setType("wait_return");
        renRZuRequest.setPer_page(15);
        renRZuRequest.setPage(1);
        int pageNum = 1 ;
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                renRZuRequest.setPage(pageNum);
                String resStr = Tool.getRequestzy(url,"",authorization, "", "", renRZuRequest);
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("order_list");
                Map<String, Object> pagination = (Map<String, Object>) dataMap.get("pagination");
                int page = Integer.parseInt(pagination.get("page").toString());
                int total = Integer.parseInt(pagination.get("total").toString());
                int pageSize = Integer.parseInt(pagination.get("page_size").toString());
                if(list != null && list.size() > 0){
                    for (Map<String, Object> item : list) {
                        //logger.info("item~~~ {}",item);
                        Map<String, Object> detail = (Map<String, Object>)item.get("base_info");
                        Map<String, Object> amountlist = (Map<String, Object>) item.get("rent_info");
                        if (detail != null && amountlist != null){
                            //订单id
                            String orderId = detail.get("order_id").toString();
                            //合同
                            List<Map<String, Object>> contract = getContractAddress(authorization,orderId);
                            //账单
                            List<Map<String, Object>> bill = renRZuBillUtil.getRenRZuBillList(authorization,orderId, cookie);
                            logger.info("bill~~"+ bill);
                            //风控
                            Map<String, Object> riskData = getRiskData(cookie,orderId);
                            // 抽离
                            orderSaveServiceImpl.extractionSave(detail,amountlist,riskData,contract,bill,orderId);
                        }
                    }
                }
                if(page*pageSize >= total){
                    logger.info("已经打印完毕");
                    break;

                }
                //休息十秒
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    logger.warn("Sleep interrupted", e);
                    Thread.currentThread().interrupt();
                }
                pageNum ++;
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
            logger.info("打印当前页码 {}",pageNum);
        }
        return listData;
    }

    //获取逾期的订单数据
    @Override
    public List<Map<String, Object>> getOverdue(String cookie) {
        String url = "https://admin.rrzu.com/bad-debt-overdue/bad-debt-list?page=";
        RenRZuRequest renRZuRequest = new RenRZuRequest();
        List<Map<String, Object>> listData = new ArrayList<>();
        renRZuRequest.setPer_page(5);
        renRZuRequest.setPage(1);
        renRZuRequest.setIs_real_count(0);
        int pageNum = 1 ;
        ObjectMapper resMapper = new ObjectMapper();
        while (true) {
            try {
                renRZuRequest.setPage(pageNum);
                //强制转string
                url = url + pageNum + "&perPage=5&is_real_count=0";
                String resStr = Tool.getRequest(url,"","", "", cookie, renRZuRequest);
                Map<String,Object> res = resMapper.readValue(resStr,Map.class);
                Map<String, Object> dataMap = (Map<String, Object>) res.get("data");
                //logger.info("dataMap {}",dataMap);
                List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("data");
                if(list != null && list.size() > 0){
                    for (Map<String, Object> item : list) {
                        //logger.info("item~~~ {}",item);
                        String orderId = item.get("order_id").toString();
                        //查询数据库中是否有此订单号，存在修改订单状态
                        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("order_id",orderId);
                        List<Orders> existingOrder = orderMapper.selectList(queryWrapper);
                        if (!existingOrder.isEmpty() ) {
                            logger.info("订单已存在~~,更新状态",orderId);
                            //更新订单状态为4
                            UpdateWrapper<Orders> updataWrapper = new UpdateWrapper<>();
                            updataWrapper.eq("order_id",orderId)
                                    .set("status",4);
                            logger.info("更新订单逾期状态成功");
                            orderMapper.update(updataWrapper);
                        }
                    }
                }
                pageNum ++;
            } catch (JsonProcessingException e) {
                logger.info(e.getMessage());
                break;
            }
            logger.info("打印当前页码 {}",pageNum);
        }
        return listData;

    }
    //订单详情
    //用户名
    public String getUserName(String authorization,String orderId) throws JsonProcessingException {
        String userUrl = rrzConfig.getGetUserUrl()+orderId+"&sign=1024&type=2&url=https%3A%2F%2Fadmin.rrzu.com%2Forder%2Fv4-order-index";
        String userNameDel = Tool.getRequest(userUrl,"",authorization, "");
        ObjectMapper userMapper = new ObjectMapper();
        Map<String,Object> userMap = userMapper.readValue(userNameDel,Map.class);
        Map<String,Object> userNameList = (Map<String, Object>) userMap.get("data");
        Map<String,Object> userNameData = (Map<String, Object>) userNameList.get("user_info");
        String userName = userNameData.get("username").toString();
        return userName;
    }
    //用户电话
    public String getUserPhone(String authorization,String orderId) throws JsonProcessingException {
        String userPhoneUrl = rrzConfig.getGetUserUrl()+orderId+"&sign=64&type=1&url=https%3A%2F%2Fadmin.rrzu.com%2Forder%2Fv4-order-index";
        String userPhoneDel = Tool.getRequest(userPhoneUrl,"",authorization, "");
        ObjectMapper userPhoneMapper = new ObjectMapper();
        Map<String,Object> userPhoneMap = userPhoneMapper.readValue(userPhoneDel,Map.class);
        Map<String,Object> userPhoneList = (Map<String, Object>) userPhoneMap.get("data");
        Map<String,Object> userPhoneData = (Map<String, Object>) userPhoneList.get("receipt_info");
        String userPhone = userPhoneData.get("desensitized_phone").toString();
        return userPhone;
    }
    //用户地址
    public String getUserAddress(String authorization,String orderId) throws JsonProcessingException {
        String userAddressUrl = rrzConfig.getGetUserUrl()+orderId+"&sign=512&type=3&url=https%3A%2F%2Fadmin.rrzu.com%2Forder%2Fv4-order-index";
        String userAddressDel = Tool.getRequest(userAddressUrl,"",authorization, "");
        ObjectMapper userAddressMapper = new ObjectMapper();
        Map<String,Object> userAddressMap = userAddressMapper.readValue(userAddressDel,Map.class);
        Map<String,Object> userAddressList = (Map<String, Object>) userAddressMap.get("data");
        Map<String,Object> userAddressData = (Map<String, Object>) userAddressList.get("receipt_info");
        String userAddress = userAddressData.get("desensitized_address").toString();
        return userAddress;
    }
    //用户身份证
    public String getUserIdcard(String authorization,String orderId) throws JsonProcessingException {
        String userIdcardUrl = rrzConfig.getGetUserUrl()+orderId+"&sign=2048&type=5&url=https%3A%2F%2Fadmin.rrzu.com%2Forder%2Fv4-order-index";
        String userIdcardDel = Tool.getRequest(userIdcardUrl,"",authorization, "");
        ObjectMapper userIdcardMapper = new ObjectMapper();
        Map<String,Object> userIdcardMap = userIdcardMapper.readValue(userIdcardDel,Map.class);
        Map<String,Object> userIdcardList = (Map<String, Object>) userIdcardMap.get("data");
        Map<String,Object> userIdcardData = (Map<String, Object>) userIdcardList.get("user_info");
        String userIdcard = userIdcardData.get("idcard").toString();
        return userIdcard;
    }
    //合同详情
    public List<Map<String, Object>> getContractAddress(String authorization,String orderId) throws JsonProcessingException {
        RenRZuRequest renRZuRequest = new RenRZuRequest();
        renRZuRequest.setPage_id(orderId);//order_id
        String contractUrl = rrzConfig.getGetContractUrl()+orderId;
        String contract = Tool.getRequest(contractUrl,"",authorization, "");
        //logger.info("合同详情 {}",contract);
        ObjectMapper resMapper = new ObjectMapper();
        Map<String,Object> res = resMapper.readValue(contract,Map.class);
        Map<String,Object> contractMap = (Map<String, Object>) res.get("data");
        //logger.info("合同详情 {}",contractMap);
        List<Map<String,Object>> contractStr = (List<Map<String, Object>>) contractMap.get("baas_evidences");
        //logger.info("合同详情 {}",contractStr);
        return contractStr;
    }
    //风控数据
    public Map<String, Object> getRiskData(String cookie, String orderId) throws JsonProcessingException {
        String riskDataUrl = rrzConfig.getGetRiskUrl()+orderId;
        String riskData = Tool.getRequest(riskDataUrl,cookie, "");
        ObjectMapper riskDataMapper = new ObjectMapper();
        Map<String,Object> riskDataMap = riskDataMapper.readValue(riskData,Map.class);
        Map<String,Object> riskDataDate = (Map<String, Object>) riskDataMap.get("data");
        Map<String,Object> riskDataInfo = (Map<String, Object>) riskDataDate.get("result_info");
        return riskDataInfo;
    }

}
